<?php

namespace app\controller\admin;

use app\base\BaseEncryptController;
use app\model\user\UserLevelModel;
use app\model\user\UserMarketModel;
use app\model\user\UserModel;
use think\Request;

/**
 * UserMarket
 * Class UserMarket
 * @package app\controller
 */
class UserMarket extends BaseEncryptController
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new UserMarketModel();
    }

    /**
     * 分页列表
     * @param int $page
     * @param int $limit
     * @return \think\response\Json
     */
    public function getPage($page = 1, $limit = 10)
    {

        $data = $this->model->getPageData($page, $limit);
        return self::returnMsg(1, [
            'totalCount' => $data['total'],
            'currentPage' => $data['current'],
            'pageList' => $data['dataList']
        ]);
    }

    /**
     * 单条信息
     * @param $id
     * @return \think\response\Json
     */
    public function getInfo($id)
    {
        $data = $this->model->getInfo($id);
        $user_model = new UserModel();
        $user_data = $user_model->getNickNameHead($data['user_id']);
        $data['nick_name'] = $user_data['nick_name'];
        $data['head_img'] = $user_data['head_img'];
        if (!empty($data)) {
            return self::returnMsg(1, $data);
        } else {
            return self::returnMsg(1001);
        }
    }

    /**
     * 保存
     * @param Request $request
     * @return \think\response\Json
     */
    public function onSave(Request $request)
    {
        $formData = [
            'id' => $request->param('id'),
            'explain' => $request->param('explain'),
            'phone' => $request->param('phone'),
            'wechat' => $request->param('wechat'),
            'status' => $request->param('status')
        ];
        if (empty($formData['id'])) {
            $validate = 'app\validate\UserMarketValidate.add';
        } else {
            $validate = 'app\validate\UserMarketValidate';
        }
        $result = $this->validate($formData, $validate);
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            $ret = $this->model->saveData($formData, false, false);
            if (false !== $ret['flag']) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        }
    }

    /**
     * 删除
     * @param $id
     * @return \think\response\Json
     */
    public function onDelete($id)
    {
        $flag = $this->model::destroy(['id' => $id]);
        if (false !== $flag) {
            $this->model->delRedis($id);
            $this->model->redis->zRem($this->model->redis_key . ':rank', $id);
            $this->model->addToRecycle($id, 'UserMarketModel', '用户推广员申请管理', $this->currentUser['user_id'], $this->currentUser['user_type'], 'user');
            return self::returnMsg(1);
        } else {
            return self::returnMsg(1002);
        }
    }
}
